<template>
  <div class="box">
    <el-breadcrumb separator-class="el-icon-arrow-right" separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="50">
          <el-col :span="8">
              <el-input
        placeholder="请输入内容"
        class="input-with-select"
        v-model="queryInfo.query"
        clearable
        @clear="getUserList"
        @change="getUserList"
      >
        <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
      </el-input>
          </el-col>
          <el-col :span="4">
              <el-button type="primary" @click="dialogVisible=true">
                  添加用户
              </el-button>
          </el-col>
      </el-row>
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch @change="userState(scope.row)" v-model="scope.row.mg_state">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip content="修改用户" placement="top" effect="dark" :enterable="false">
              <el-button @click="amendUser(scope.row.id)" size="mini"  type="primary" icon="el-icon-edit"></el-button>
            </el-tooltip>
            <el-tooltip content="删除用户" placement="top" effect="dark" :enterable="false">
              <el-button @click="delUser(scope.row.id)" size="mini" type="danger" icon="el-icon-delete"></el-button>
            </el-tooltip>
            <el-tooltip content="分配权限" placement="top" effect="dark" :enterable="false">
              <el-button @click="userRoles(scope.row)" size="mini" type="warning" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination 
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1,2,3,4]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </el-card>

    <!-- dialog对话框 -->
    <el-dialog
    title="添加用户"
    :visible.sync="dialogVisible"
    width="50%"
    @close="addDialogClose">
      <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密 码" prop="password">
          <el-input type="password" v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮 箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手 机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addUser">确 定</el-button>
    </span>
  </el-dialog>
  <el-dialog
    title="修改用户信息"
    :visible.sync="amdUser"
    width="50%"
    @close="amdDialogClose">
    <el-form :model="amdForm" ref="amdFormRef" :rules="amdRules" label-width="70px">
      <el-form-item label="用户名">
        <el-input disabled v-model="amdForm.username"></el-input>
      </el-form-item>
      <el-form-item label="邮 箱" prop="email">
        <el-input v-model="amdForm.email"></el-input>
      </el-form-item>
      <el-form-item label="电 话" prop="mobile">
        <el-input v-model="amdForm.mobile"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button @click="amdUser = false">取 消</el-button>
      <el-button type="primary" @click="amdUserInfo">确 认</el-button>
    </span>
  </el-dialog>
  <!-- 分配角色对话框 -->
<el-dialog
  title="角色分配"
  :visible.sync="rolesInfo"
  width="50%"
  @close="rolesClose">
  <div>
    <p>当前用户：{{userInfo.username}}</p>
    <p>当前角色：{{userInfo.role_name}}</p>
    <p>分配角色；
      <el-select v-model="selectedRoleId" placeholder="请选择">
        <el-option
          v-for="item in rolesList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id">
        </el-option>
      </el-select>
    </p>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="rolesInfo = false">取 消</el-button>
    <el-button type="primary" @click="rolesDialog">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
    data() {
      // 添加自定义校验规则
      var checkEmail = (rule, value, callback)=>{
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
        if(!value) {
          return callback(new Error('邮箱不能为空'))
        }else if(!regEmail.test(value)){
          return callback(new Error('邮箱格式错误'))
        }else {
          return callback()
        }
      }
      var checkPhone = (rule, value, callback)=>{
        const regMobile = /^(1[3-9][0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
        if(!value) {
          return callback(new Error('手机号码不能为空'))
        }else if(!regMobile.test(value)){
          return callback(new Error('手机号码格式错误'))
        }else {
          return callback()
        }
      }



      return {
        queryInfo: {
          query: '',
          // 当前页数
          pagenum: 1,
          pagesize: 4
        },
        userList:[],
        total: 0,
        dialogVisible: false,
        amdUser: false,
        addForm: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        amdForm: {},
        // 添加用户表单验证
        rules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            {
              min: 3,
              max: 6,
              message: '长度在 3 到 6 个字符',
              trigger: 'blur',
            },
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur'},
            {
              min: 6,
              message: '最小六个字符',
              trigger: 'blur'
            }
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur'},
            { validator: checkEmail, trigger: 'blur'}
          ],
          mobile: [
            { required: true, message: '请输入手机号码', trigger: 'blur'},
            { validator: checkPhone, trigger: 'blur'}
          ]
        },
        // 修改用户信息表单验证
        amdRules: {
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur'},
            { validator: checkEmail, trigger: 'blur'}
          ],
          mobile: [
            { required: true, message: '请输入手机号码', trigger: 'blur'},
            { validator: checkPhone, trigger: 'blur'}
          ]
        },
        rolesInfo: false,
        userInfo: {},
        rolesList: [],
        selectedRoleId: ''
      }
    },
    created() {
      this.getUserList()
    },
    methods: {
      async getUserList() {
        const {data:res} = await this.$http.get('/users', {params: this.queryInfo})
        if (res.meta.status !== 200) {
          return this.$message.error('获取用户列表失败')
        }
        this.userList = res.data.users
        this.total = res.data.total
      },

      // 监听一页显示几条数据
      handleSizeChange(newSize) {
        this.queryInfo.pagesize=newSize
        this.getUserList()
      },
      handleCurrentChange(newPage) {
        this.queryInfo.pagenum = newPage
        this.getUserList()
      },
      // 监听用户状态
      async userState(val) {
        const {data:res} = await this.$http.put(`/users/${val.id}/state/${val.mg_state}`)
        if(res.meta.status !== 200){
          val.mg_state = !val.mg_state
          return this.$message.error('更改用户状态失败！')
        }
        this.$message.success('更改用户状态成功')
      },
      // 监听弹窗关闭事件
      addDialogClose() {
        // 关闭对话框重置表单
        this.$refs.addFormRef.resetFields()
      },
      // 点击确认与验证
      addUser() {
        this.$refs.addFormRef.validate(async valid=>{
          if(!valid) return
          const {data:res} = await this.$http.post('/users', this.addForm)
          if(res.meta.status!==201){
            this.$message.error('添加用户成功')
          }
          this.$message.success('添加用户成功')
          this.dialogVisible = false
          this.getUserList()
        })
      },
      // 点击修改用户按钮弹出对话框并获取信息
      async amendUser(v) {
        const {data:res} = await this.$http.get('/users/'+v)
        if(res.meta.status !== 200) {
          return this.$message.error('查询用户信息失败！')
        }
        this.amdForm = res.data
        this.amdUser = true
      },
      // 点击关闭对话框重置
      amdDialogClose() {
        this.$refs.amdFormRef.resetFields()
      },
      // 点击确认修改用户信息，并刷新列表
      amdUserInfo() {
        this.$refs.amdFormRef.validate(async valid=>{
          if(!valid) return
          const {data:res} = await this.$http.put('/users/'+this.amdForm.id, {
            email:this.amdForm.email,
            mobile: this.amdForm.mobile
          })
          if(res.meta.status!==200){
            return this.$message.error('更新用户信息失败！')
          }
          this.amdUser = false
          this.getUserList()
          this.$message.success('更新用户信息成功')
        })
      },
      // 点击删除按钮删除用户信息
      async delUser(id) {
        const confirmUser = await this.$confirm('此操作将永久删除用户，是否继续？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        // 点击取消返回 cancel ，点击确认返回 confirm 
        if(confirmUser!=='confirm') {
          return this.$message.info('取消删除')
        }
        const {data:res} = await this.$http.delete('/users/'+id)
        if(res.meta.status!==200){
          return this.$message.error('删除用户信息失败！')
        }
        this.$message.success('该用户已删除！')
        this.getUserList()
      },
      // 分配角色
      async userRoles(userInfo) {
        this.userInfo = userInfo
        const {data:res} = await this.$http.get('/roles')
        if(res.meta.status!==200){
          return this.$message.error('获取角色列表失败！')
        }
        this.rolesList = res.data
        this.rolesInfo = true
      },
      async rolesDialog() {
        if(!this.selectedRoleId){
          return this.$message.error('请选择要分配的角色！')
        }
        const {data:res} = await this.$http.put(`/users/${this.userInfo.id}/role`, {rid: this.selectedRoleId})
        if(res.meta.status!==200){
          return this.$message.error('分配角色失败！')
        }
        this.$message.success('角色分配成功！')
        this.getUserList()
        this.rolesInfo = false
      },
      rolesClose() {
        this.selectedRoleId = ''
        this.userInfo = {}
      }
    }
}
</script>

<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 10px;
}
</style>